package com.audaque.springboot.foshanupload.web.esdatademo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.http.HttpHost;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.elasticsearch.client.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author zgb
 * @desc ...
 * @date 2023-06-12 20:30:11
 */
@Api(tags = "增删改查（文档）")
@RestController
@RequestMapping("restClient")
public class RestClientController {
    @Autowired
    RestClient restClient;

    @ApiOperation("低级查询")
    @GetMapping("lowLevel")
    public void lowLevel() throws Exception{

        // 4.构建请求
        Request request = new Request("Get", "/blog/_search");
        // 5.添加请求参数
        request.addParameter("pretty", "true");
        // 添加请求体
        request.setEntity(new NStringEntity("{\"query\": {\"term\": {\"title\": {\"value\": \"1\"}}}}", ContentType.APPLICATION_JSON));
        // 6.发起同步请求，同步请求会阻塞后面的代码
        Response response = null;

        response = restClient.performRequest(request);

        // 7.解析 response，获取响应结果
        BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String str = null;
        while ((str = br.readLine()) != null) {
            System.out.println(str);
        }
        br.close();
        // 8.关闭 RestClient
        restClient.close();
    }

    @ApiOperation("低级异步查询")
    @GetMapping("lowLevelAnsy")
    public void lowLevelAnsy() throws Exception{
            // 1.构建一个 RestClientBuilder 对象，里面添加三台 ElasticSearch 服务信息
            RestClientBuilder builder = RestClient.builder(
                    new HttpHost("localhost", 9200, "http"),
                    new HttpHost("localhost", 9201, "http"),
                    new HttpHost("localhost", 9202, "http")
            );
            // 2.如果需要在请求头中设置认证信息，可以通过 builder 来设置
            // builder.setDefaultHeaders(new Header[]{new BasicHeader("key", "value")});
            // 3.构建 RestClient 对象
            RestClient restClient = builder.build();
            // 4.构建请求
            Request request = new Request("Get", "/books/_search");
            // 5.添加请求参数
            request.addParameter("pretty","true");
            // 添加请求体
            request.setEntity(new NStringEntity("{\"query\": {\"term\": {\"name\": {\"value\": \"java\"}}}}", ContentType.APPLICATION_JSON));
            // 6.发起异步请求，配置响应监听器
            restClient.performRequestAsync(request, new ResponseListener() {
                //请求成功的回调
                @SneakyThrows
                @Override
                public void onSuccess(Response response) {
                    // 7.解析 response，获取响应结果
                    BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                    String str = null;
                    while ((str = br.readLine()) != null) {
                        System.out.println(str);
                    }
                    br.close();
                    // 8.关闭 RestClient
                    restClient.close();
                }

                //请求失败的回调
                @Override
                public void onFailure(Exception e) {
                    e.printStackTrace();
                }
            });
        }


}
